package com.yanyu.space.sys.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yanyu.space.common.core.bean.db.PageEntity;
import com.yanyu.space.common.core.bean.web.R;
import com.yanyu.space.sys.bean.po.DicItem;
import com.yanyu.space.sys.bean.vo.dicItem.DicItemInfoVo;
import com.yanyu.space.sys.bean.vo.dicItem.DicItemSearchVo;
import com.yanyu.space.sys.bean.enums.EnabledEnum;
import com.yanyu.space.sys.service.IDicItemService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 数据字典项 前端控制器
 *
 * @author yanyu
 */
@RestController
@RequestMapping("/sys/dic/item")
@Api(tags = "系统字典项")
@AllArgsConstructor
@Validated
public class DicItemController {

    private IDicItemService dicItemService;

    @GetMapping("/list")
    @ApiOperation("查询数据字典项列表")
    public R<PageEntity<DicItem>> list(DicItemSearchVo vo) {
        return R.ok(dicItemService.listPage(vo));
    }

    @GetMapping("/{id}")
    @ApiOperation("根据id数据字典项")
    public R<DicItem> getById(@PathVariable("id") Long id) {
        return R.ok(dicItemService.getById(id));
    }

    @PostMapping
    @ApiModelProperty("新增数据字典项")
    public R add(@RequestBody DicItem dicItem) {
        dicItemService.save(dicItem);
        return R.ok();
    }

    @PutMapping
    @ApiOperation("修改数据字典项")
    public R udpateById(@RequestBody DicItem dicItem) {
        dicItemService.updateById(dicItem);
        return R.ok();
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除数组字典项")
    public R deleteById(@PathVariable("id") Long id) {
        dicItemService.removeById(id);
        return R.ok();
    }

    @GetMapping("/code/{code}")
    @ApiOperation("查询数据字典项")
    public R<List<DicItemInfoVo>> listDicItemByCode(@PathVariable("code") String code) {
        List<DicItem> dicItems =
                dicItemService.list(Wrappers.<DicItem>lambdaQuery()
                        .eq(DicItem::getCode, code)
                        .eq(DicItem::getEnabled, EnabledEnum.YES.getValue())
                        .orderByAsc(DicItem::getSort));
        return R.ok(BeanUtil.copyToList(dicItems, DicItemInfoVo.class));
    }
}

